<template>
  <div>
    <UploadExcel :on-success="onSuccess" />
  </div>
</template>

<script>
// 导入批量导入员工请求接口
import { importEmployeeAPI } from '@/api/employees'
// 导入枚举数据
import EmployeeEnum from '@/constant/employees'
export default {
  methods: {
    async onSuccess({ header, results }) {
      // console.log(header)
      // console.log(results)
      // 处理获取到的Excel表格数据
      const data = results.map(item => {
        const user = {}
        user.timeOfEntry = new Date(this.formatDate(item['入职日期'], '/'))
        user.mobile = item['手机号']
        user.username = item['姓名']
        user.departmentName = item['部门']
        // 处理导入时聘用形式数据，因为后端需要传递的是1或0
        const obj = EmployeeEnum.hireType.find(el => el.value === item['聘用形式'])
        // console.log(obj)
        const formOfEmployment = obj ? Number(obj.id) : ''
        user.formOfEmployment = formOfEmployment

        user.correctionTime = new Date(this.formatDate(item['转正日期'], '/'))
        user.workNumber = item['工号']
        return user
      })
      // 再次确认导入操作
      await this.$confirm(`导入成功！共 ${data.length} 个员工！确定要新增吗？`)
      // 发送批量新增请求
      await importEmployeeAPI(data)
      // 导入成功提示
      this.$message.success('导入成功！')
      // 返回上一级页面
      this.$router.back()
    },
    // 封装处理Excel表格5位数日期的函数
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style>

</style>
